<template>
  <el-dialog
    :model-value="visible"
    :title="mode === 'create' ? '新增产品' : '编辑产品'"
    width="900px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入产品名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品分类" prop="category">
            <el-select v-model="form.category" placeholder="请选择产品分类" style="width: 100%">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="单价(元)" prop="unitPrice">
            <el-input-number
              v-model="form.unitPrice"
              :min="0.01"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存数量" prop="stock">
            <el-input-number
              v-model="form.stock"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制作时间(分钟)" prop="productionTime">
            <el-input-number
              v-model="form.productionTime"
              :min="1"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="难度等级" prop="difficulty">
            <el-rate
              v-model="form.difficulty"
              show-text
              :texts="['简单', '普通', '中等', '困难', '专家']"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">可领取</el-radio>
              <el-radio :label="0">已下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="制作工具">
        <div class="tools-input">
          <el-tag
            v-for="tool in form.tools"
            :key="tool"
            closable
            @close="removeTool(tool)"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ tool }}
          </el-tag>
          <el-input
            v-if="toolInputVisible"
            ref="toolInputRef"
            v-model="toolInputValue"
            size="small"
            style="width: 120px"
            @keyup.enter="addTool"
            @blur="addTool"
          />
          <el-button
            v-else
            size="small"
            @click="showToolInput"
          >
            + 添加工具
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="产品图片" prop="images">
        <div class="image-upload">
          <div class="upload-list">
            <div
              v-for="(image, index) in form.images"
              :key="index"
              class="upload-item"
            >
              <el-image
                :src="image"
                fit="cover"
                class="upload-image"
              />
              <div class="upload-actions">
                <el-icon class="delete-icon" @click="removeImage(index)"><Delete /></el-icon>
              </div>
            </div>
            <div class="upload-trigger" @click="handleImageUpload">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">上传图片</div>
            </div>
          </div>
          <input
            ref="imageInput"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleImageChange"
          />
        </div>
      </el-form-item>

      <el-form-item label="制作演示视频">
        <div class="video-upload">
          <div v-if="form.videoUrl" class="video-preview">
            <video
              :src="form.videoUrl"
              controls
              style="width: 200px; height: 150px; border-radius: 4px"
            />
            <el-button type="danger" size="small" @click="removeVideo">删除视频</el-button>
          </div>
          <div v-else class="upload-trigger" @click="handleVideoUpload">
            <el-icon class="upload-icon"><VideoPlay /></el-icon>
            <div class="upload-text">上传视频</div>
          </div>
          <input
            ref="videoInput"
            type="file"
            accept="video/*"
            style="display: none"
            @change="handleVideoChange"
          />
        </div>
      </el-form-item>

      <el-form-item label="配件清单">
        <div class="accessories-list">
          <div v-for="(accessory, index) in form.accessoriesList" :key="index" class="accessory-item">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-input
                  v-model="accessory.name"
                  placeholder="配件名称"
                  size="small"
                />
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="accessory.quantity"
                  placeholder="数量"
                  size="small"
                />
              </el-col>
              <el-col :span="4">
                <el-input
                  v-model="accessory.unit"
                  placeholder="单位"
                  size="small"
                />
              </el-col>
              <el-col :span="6">
                <el-button type="danger" size="small" @click="removeAccessory(index)">
                  删除
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" size="small" @click="addAccessory">
            + 添加配件
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="产品描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入产品描述，包括制作要求、注意事项等"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ mode === 'create' ? '创建' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete, VideoPlay } from '@element-plus/icons-vue'
import { productAPI } from '@/api/product'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'create',
    validator: (value) => ['create', 'edit'].includes(value)
  },
  data: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const imageInput = ref()
const videoInput = ref()
const toolInputRef = ref()
const loading = ref(false)
const categories = ref([])
const toolInputVisible = ref(false)
const toolInputValue = ref('')

const form = reactive({
  name: '',
  category: '',
  unitPrice: 0,
  stock: 0,
  productionTime: 60,
  difficulty: 1,
  status: 1,
  tools: [],
  images: [],
  videoUrl: '',
  accessoriesList: [],
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 1, max: 100, message: '产品名称长度为1-100个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择产品分类', trigger: 'change' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
  ],
  productionTime: [
    { required: true, message: '请输入制作时间', trigger: 'blur' },
    { type: 'number', min: 1, message: '制作时间必须大于0', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择产品状态', trigger: 'change' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 获取产品分类
const fetchCategories = async () => {
  try {
    const response = await productAPI.getCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取产品分类失败:', error)
  }
}

// 添加工具
const addTool = () => {
  const tool = toolInputValue.value.trim()
  if (tool && !form.tools.includes(tool)) {
    form.tools.push(tool)
  }
  toolInputVisible.value = false
  toolInputValue.value = ''
}

// 移除工具
const removeTool = (tool) => {
  const index = form.tools.indexOf(tool)
  if (index > -1) {
    form.tools.splice(index, 1)
  }
}

// 显示工具输入框
const showToolInput = () => {
  toolInputVisible.value = true
  nextTick(() => {
    toolInputRef.value?.focus()
  })
}

// 处理图片上传点击
const handleImageUpload = () => {
  imageInput.value?.click()
}

// 处理图片选择
const handleImageChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      form.images.push(e.target.result)
    }
    reader.readAsDataURL(file)
  }
  event.target.value = ''
}

// 移除图片
const removeImage = (index) => {
  form.images.splice(index, 1)
}

// 处理视频上传点击
const handleVideoUpload = () => {
  videoInput.value?.click()
}

// 处理视频选择
const handleVideoChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      form.videoUrl = e.target.result
    }
    reader.readAsDataURL(file)
  }
  event.target.value = ''
}

// 移除视频
const removeVideo = () => {
  form.videoUrl = ''
}

// 添加配件
const addAccessory = () => {
  form.accessoriesList.push({
    name: '',
    quantity: '',
    unit: ''
  })
}

// 移除配件
const removeAccessory = (index) => {
  form.accessoriesList.splice(index, 1)
}

// 监听props变化
watch(() => props.visible, (visible) => {
  if (visible) {
    fetchCategories()
    if (props.mode === 'edit' && props.data) {
      Object.assign(form, {
        name: props.data.name || '',
        category: props.data.category || '',
        unitPrice: props.data.unitPrice || 0,
        stock: props.data.stock || 0,
        productionTime: props.data.productionTime || 60,
        difficulty: props.data.difficulty || 1,
        status: props.data.status ?? 1,
        tools: [...(props.data.tools || [])],
        images: [...(props.data.images || [])],
        videoUrl: props.data.videoUrl || '',
        accessoriesList: [...(props.data.accessoriesList || [])],
        description: props.data.description || ''
      })
    } else {
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    category: '',
    unitPrice: 0,
    stock: 0,
    productionTime: 60,
    difficulty: 1,
    status: 1,
    tools: [],
    images: [],
    videoUrl: '',
    accessoriesList: [],
    description: ''
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    const submitData = { ...form }

    if (props.mode === 'create') {
      await productAPI.create(submitData)
      ElMessage.success('产品创建成功')
    } else {
      await productAPI.update(props.data.id, submitData)
      ElMessage.success('产品更新成功')
    }

    emit('success')
  } catch (error) {
    console.error('保存产品失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.tools-input {
  .el-tag {
    margin-bottom: 8px;
  }
}

.image-upload {
  .upload-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
  }

  .upload-item {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 6px;
    overflow: hidden;

    .upload-image {
      width: 100%;
      height: 100%;
      display: block;
    }

    .upload-actions {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;

      &:hover {
        opacity: 1;
      }

      .delete-icon {
        color: white;
        font-size: 20px;
        cursor: pointer;
      }
    }
  }

  .upload-trigger {
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .upload-icon {
      font-size: 24px;
      color: #8c939d;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
    }
  }
}

.video-upload {
  .video-preview {
    display: flex;
    align-items: center;
    gap: 12px;

    video {
      border-radius: 4px;
    }
  }

  .upload-trigger {
    width: 200px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .upload-icon {
      font-size: 24px;
      color: #8c939d;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
    }
  }
}

.accessories-list {
  .accessory-item {
    margin-bottom: 12px;
    padding: 12px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background-color: #fafafa;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>